package cn.smile.util;

import cn.smile.bean.CodeMsg;
import cn.smile.bean.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.Date;
import java.util.Objects;

@Slf4j
public class FIleUtil {

    /**
     * 图片上传处理类
     */
    public static Result<String> uploadPhoto(MultipartFile photo, String uploadPhotoSuffix, Long uploadPhotoMaxSize, String uploadPhotoPath) {
        //判断文件类型是否是图片
        String originalFilename = photo.getOriginalFilename();
        if (Objects.isNull(originalFilename)) {
            return Result.error(CodeMsg.UPLOAD_PHOTO_SUFFIX_ERROR);
        }
        //获取文件后缀
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
        if (!uploadPhotoSuffix.contains(suffix.toLowerCase())) {
            return Result.error(CodeMsg.UPLOAD_PHOTO_SUFFIX_ERROR);
        }
        if (photo.getSize() / 1024 > uploadPhotoMaxSize) {
            CodeMsg codeMsg = CodeMsg.UPLOAD_PHOTO_ERROR;
            codeMsg.setMsg("图片大小不能超过" + (uploadPhotoMaxSize / 1024) + "M");
            return Result.error(codeMsg);
        }
        //准备保存文件
        File filePath = new File(uploadPhotoPath);
        if (!filePath.exists()) {
            //若不存在文件夹，则创建一个文件夹
            boolean mkdir = filePath.mkdir();
            log.info("图片文件夹创建完成, mkdir = {}", mkdir);
        }
        filePath = new File(uploadPhotoPath + "/" + StringUtil.getFormatterDate(new Date(), "yyyyMMdd"));
        //判断当天日期的文件夹是否存在，若不存在，则创建
        if (!filePath.exists()) {
            //若不存在文件夹，则创建一个文件夹
            boolean mkdir = filePath.mkdir();
            log.info("图片文件夹创建完成, mkdir = {}", mkdir);
        }
        String filename = StringUtil.getFormatterDate(new Date(), "yyyyMMdd") + "/" + System.currentTimeMillis() + suffix;
        try {
            photo.transferTo(new File(uploadPhotoPath + "/" + filename));
        } catch (Exception e) {
            log.error("图片文件保存异常, e: ", e);
        }
        log.info("图片上传成功，保存位置：{}", uploadPhotoPath + filename);
        return Result.success(filename);
    }
}
